package com.arvato.minipro.controller.front.mall;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.arvato.minipro.bean.bean_do.mall.EcCutDo;
import com.arvato.minipro.bean.bean_do.mall.EcOrderDo;
import com.arvato.minipro.bean.bean_dto.common.PageData;
import com.arvato.minipro.bean.bean_dto.common.Query;
import com.arvato.minipro.bean.bean_dto.common.Result;
import com.arvato.minipro.bean.bean_vo.user.EcUserVo;
import com.arvato.common.config_bean.WxPayConfig;
import com.arvato.common.wx.crypt.AesException;
import com.arvato.minipro.controller.BaseController;
import com.arvato.minipro.service.mall.CutDownService;
import com.arvato.minipro.service.mall.OrderService;
import com.arvato.minipro.service.mall.PayService;
import com.arvato.minipro.service.mall.ShoppingCartService;
import com.arvato.minipro.service.user.CardService;
import com.arvato.minipro.service.user.EcUserService;

/**
 * 
 * @author: smallking
 * 
 * @Descibe: 订单付款相关的Controller
 * 
 * @Date: 2018年5月22日 下午3:19:27
 */
@Controller
@RequestMapping(value = "/mall/order")
public class OrderController extends BaseController{

	private Logger logger = LoggerFactory.getLogger(OrderController.class);
	
	@Autowired
	private PayService payService;

	@Autowired
	private EcUserService userService;
	
	@Autowired
	private OrderService orderService;
	
	@Autowired
	private ShoppingCartService shoppingCartService;
	
	@Autowired
	private CutDownService cutDownService;
	
	@Autowired
	private CardService cardService;
	
	/**
	 * 查询订单列表
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/list", method = { RequestMethod.POST })
	public PageData listOrder(String userId) {
		Query query = new Query();
		query.put("buyerId", userId);
		PageData pageData = orderService.listOrderByQuery(query);
		pageData.setFront(true);
		return pageData;
	}
	
	
	/**
	 * 创建订单
	 * @param userId 用户Id
	 * @param method cart， commodityInfo， cut三个值
	 * @param commodityInfoStr method = cart时候 商品信息 
	 * @param buyerMessage 
	 * @param postFee
	 * @param cutId method = cut时候的砍价ID
	 * @param integral 是否使用了积分
	 * @param deductPoint 使用的积分数
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/insert", method = { RequestMethod.POST })
	public Result createOrder(String userId, String commodityInfoStr, String buyerMessage, String postFee, String method, String cutId, boolean integral, int deductPoint) {
		Result result = new Result(false);
		if(userId == null) {
			return result;
		}
		EcUserVo userVo = userService.getUserById(userId);
		String openId = userVo.getWxOpenid();
		if(openId == null || commodityInfoStr == null) {
			return result;
		}
		
		// 首先在自己的数据库存入此条订单信息
		EcOrderDo orderDo = new EcOrderDo();
		orderDo.setBuyerId(userId);
		orderDo.setBuyerMessage(buyerMessage);
		orderDo.setOrderNo(System.currentTimeMillis() + "");
		orderDo.setCreateTime(new Date());
		orderDo.setPaymentTime(new Date());
		orderDo.setPostFee(postFee);
		orderDo.setRate(0);
		orderDo.setSellerId(WxPayConfig.APPID);
		orderDo.setStatus(1);
		orderDo.setPayment("1");
		try {
			int row = orderService.insert(orderDo, commodityInfoStr);
			if(row == 1) {
				// 如果数据库订单记录插入成功，就向微信发送付款申请
				result = payService.prePay(openId, orderDo.getOrderNo(), orderDo.getOrderId(), 1);
				if(result.getCode() == 200) {
					try {
						// 判断是否使用了积分
						if(integral){
							// 如果使用了积分 就扣除用户的积分
							cardService.updateBonus(userId, -deductPoint , "线上购物消耗" + deductPoint + "积分");
						}
						// 购物得积分 现在就一笔订单五个积分把
						cardService.updateBonus(userId, 100 , "支付订单得" + 100 + "积分");
					} catch (Exception e) {
						e.printStackTrace();
						logger.error("更新积分出错", e);
					}
					// 付款成功 如果当前是购物车过来的订单 就删除购物车记录 
					if("cart".equals(method)) {
						Query query = new Query();
						query.put("userId", userId);
						String[] split = commodityInfoStr.split("&");
						for(String str : split) {
							String commodityId = str.split(",")[0];
							query.put("commodityId", commodityId);
							shoppingCartService.deleteByQuery(query);
						}	
					}else if("cut".equals(method)) {
						// 如果是砍价过来的 就改变砍价状态
						EcCutDo cutDo = new EcCutDo();
						cutDo.setCutId(cutId);
						cutDo.setStatus(3);
						cutDownService.update(cutDo);
					}
					// 然后改变订单的状态
					EcOrderDo order1 = new EcOrderDo();
					order1.setOrderId(orderDo.getOrderId());
					// 状态 2：已付款 待发货
					order1.setStatus(2);
					orderService.update(order1);
				}
				return result;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 付款之后 微信推送支付结果到此接口
	 * 
	 * @param param
	 * @return
	 * @throws AesException 
	 */
	@ResponseBody
	@RequestMapping(value = "/notify", method = {RequestMethod.POST })
	public String payResult(HttpServletRequest req) throws AesException {
		StringBuffer url = req.getRequestURL();
		// 得到微信推送携带的参数
		// 签名 验证消息没有被中间人篡改过
		String signature = req.getParameter("msg_signature");
		// 时间戳
		String timestamp = req.getParameter("timestamp");
		// 随机字符串 签名用盐
		String nonce = req.getParameter("nonce");
		// post推送的ticket数据
		String postData = super.getRequestStr(req).trim();
		logger.info("访问者URl：" + getIpAddr(req) + " " + url);
		logger.info("URL参数：" + signature + "  " + timestamp + " " + nonce);
		logger.info("post密文：" + postData);
		return "<xml>"
				+ "<return_code>"
				+ "<![CDATA[SUCCESS]]>"
				+ "</return_code>"
				+ "<return_msg>"
				+ "<![CDATA[OK]]>"
				+ "</return_msg>"
				+ "</xml>";
	}
}
